/**
 * 
 */
package com.disys.examples;

/**
 * @author Ubaid Raja
 *
 */
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.*;

public class UserFetch {
	private static int total;
	private static int count;

	public static void main(String[] args) {
		try {
			// Activate paged results
			byte[] cookie = null;
			setCount(0);

			try {
				Properties prop = new Properties();
				ClassLoader loader = Thread.currentThread()
						.getContextClassLoader();
				InputStream stream = loader
						.getResourceAsStream("ldap.properties");
				prop.load(stream);

				// get the property value and print it out
				System.out.println(prop.getProperty("INITIAL_CONTEXT_FACTORY"));
				System.out.println(prop.getProperty("SECURITY_AUTHENTICATION"));
				System.out.println(prop.getProperty("SECURITY_CREDENTIALS"));
				System.out.println(prop.getProperty("PROVIDER_URL"));

			} catch (IOException ex) {
				ex.printStackTrace();
			}

			Hashtable<String, String> env = new Hashtable<String, String>();

			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.REFERRAL, "follow");
			env.put(Context.SECURITY_AUTHENTICATION, "Simple");
			env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
			env.put(Context.SECURITY_CREDENTIALS, "secret");
			env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
			LdapContext ctx = new InitialLdapContext(env, null);

			ctx.setRequestControls(new Control[] { new PagedResultsControl(
					10000, Control.CRITICAL) });

			do {
				// Perform the search
				NamingEnumeration results = ctx.search("dc=elixir,dc=com",
						"(&(objectclass=person))", getSimpleSearchControls());

				// Iterate over a batch of search results
				while (results != null && results.hasMore()) {
					// Display an entry
					SearchResult entry = (SearchResult) results.next();
					Attributes attrs = entry.getAttributes();
					System.out.println("cn: " + attrs.get("cn"));
					System.out.println("sn: " + attrs.get("sn")); // lastname
					// Handle the entry's response controls (if any)
				}
				// Examine the paged results control response
				Control[] controls = ctx.getResponseControls();
				if (controls != null) {
					for (int i = 0; i < controls.length; i++) {
						if (controls[i] instanceof PagedResultsResponseControl) {
							PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
							setTotal(prrc.getResultSize());
							cookie = prrc.getCookie();
						} else {
							// Handle other response controls (if any)
						}
					}
				}

				// Re-activate paged results
				ctx.setRequestControls(new Control[] { new PagedResultsControl(
						10000, cookie, Control.CRITICAL) });
			} while (cookie != null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SearchControls getSimpleSearchControls() {
		SearchControls searchControls = new SearchControls();
		searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		searchControls.setTimeLimit(30000);
		String[] attrIDs = { "cn", "sn" };

		searchControls.setReturningAttributes(attrIDs);
		return searchControls;
	}

	public static int getTotal() {
		return total;
	}

	public static void setTotal(int total) {
		UserFetch.total = total;
	}

	public static int getCount() {
		return count;
	}

	public static void setCount(int count) {
		UserFetch.count = count;
	}

}
